<?php


namespace App\Http\Controllers\Admin;
use App\Http\Controllers\BaseController;
use App\Models\Order;
use Dingo\Api\Http\Request;

class OrderController extends BaseController
{

    public function index(Request $request)
    {
        $order_sn = $request->input('order_sn');
        $category_id = $request->input('category_id');
        $start_at = $request->input('start_at');
        $end_at = $request->input('end_at');
        $merchant_phone = $request->input('merchant_phone');
        $nickname = $request->input('nickname');
        $rec_merchant_contact = $request->input('rec_merchant_contact');

        $list = Order::where('product_type', Order::PRODUCT_TYPE_COOKBOOK)->where('status', Order::PAID_SUCCESS)->startAt($start_at)->endAt($end_at)
            ->orderSn($order_sn)->when($merchant_phone, function ($q) use($merchant_phone){
                $q->whereHas('merchant', function ($qr) use($merchant_phone) {
                    $qr->where('phone', 'like', '%'.$merchant_phone.'%');
                });
            })->when($nickname, function ($q) use($nickname){
                $q->whereHas('user', function ($qr) use($nickname) {
                    $qr->where('nickname', 'like', '%'.$nickname.'%');
                });
            })->when($rec_merchant_contact, function ($q) use($rec_merchant_contact){
                $q->whereHas('rec_merchant', function ($qr) use($rec_merchant_contact) {
                    $qr->where('contact', 'like', '%'.$rec_merchant_contact.'%');
                });
            })->when($category_id, function ($q) use($category_id){
                $q->where('category_id', $category_id);
            })
            ->withCertain('cookbook', ['title', 'short_title'])
            ->withCertain('category', ['title'])
            ->withCertain('user', ['nickname', 'avatar_url'])
            ->withCertain('rec_merchant', ['contact'])
            ->withCertain('merchant', ['contact', 'phone'])->orderBy("id", "desc")
            ->paginate(\request('per_page', 20));
        return $this->paginate($list);
    }

}

